﻿namespace SalaryTool.Service
{
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.IO;
    using System.Linq;
    using System.Web;
    using System.Xml.Serialization;
    using SalaryTool.Service.Models;

    public static class SalaryCalculator
    {
        private static string salaryDataFilePath;

        static SalaryCalculator()
        {
            salaryDataFilePath = ConfigurationManager.AppSettings["salaryDataFile"];

            try
            {
                salaryDataFilePath = HttpContext.Current.Server.MapPath(salaryDataFilePath);
            }
            catch (HttpException)
            {
            }
            catch (NullReferenceException)
            {
            }
        }

        public static float CalculateSalary(int level, int marketMultiplier)
        {
            Salary currentSalary = GetSalaryFromFile(level);

            float marketAverage = currentSalary.AverageSalary;

            return (float)(marketAverage + (marketAverage * (marketMultiplier / 100.0)));
        }

        private static Salary GetSalaryFromFile(int level)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(List<Salary>));

            Salary currentSalary = null;

            using (StreamReader reader = new StreamReader(salaryDataFilePath))
            {
                List<Salary> salaries = serializer.Deserialize(reader) as List<Salary>;

                currentSalary = salaries.SingleOrDefault(s => s.Level == level);
            }

            return currentSalary;
        }
    }
}